package com.itheima.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.Order;
import com.itheima.domain.Product;
import com.itheima.exception.BlockException;
import com.itheima.service.OrderService;
import com.itheima.service.ProductService;
import com.sun.org.apache.xpath.internal.operations.Or;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.nio.Buffer;
import java.util.List;
import java.util.Random;

/**
 * UserController
 *
 * @author jjh
 * @date 2020/2/22
 **/
@Slf4j
//@RestController
public class OrderController1 {

    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductService productService;

    @Autowired
    private DiscoveryClient discoveryClient;

    int i = 0;

    /**
     * 下单
     * ribbon+feign
     * @return
     */
    @RequestMapping("/order/prod/{pid}")
    public Order order(@PathVariable("pid") Integer pid)  {
        log.info("接收到{}商品的下单请求，接下来调用商品微服务查询商品信息", pid);

        Product product = productService.findByPid(pid);

        if (product.getPid() == -100) {
            Order order = new Order();
            order.setOid(-100);
            order.setContent("下单失败");
            return order;
        }

//        try {
//            Thread.sleep(2000L);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        log.info("查询到{}商品的信息：{}",pid, JSON.toJSONString(product));

        // 下单
        Order order = new Order();
        order.setUid(1);
        order.setPid(pid);
        order.setNumber(1);
        order.setPrice(product.getPrice());

        orderService.create(order);

        // 投递消息
        rocketMQTemplate.convertAndSend("order-topic", order);

        return order;
    }

    @RequestMapping("/order/message")
    public String message()  {
        i ++;
        if (i % 3 == 0) {
            throw new RuntimeException("测试异常");
        }
        return "success";
    }

    @RequestMapping("/order/message1")
    public String message1()  {
        return "success1";
    }

    @SentinelResource(value = "message2", blockHandler = "myBlockHandler", fallback = "myThrowable")
    @RequestMapping("/order/message2")
    public String message2(String name)  {
        return "success2";
    }

    @SentinelResource("message3")
    @RequestMapping("/order/message3")
    public String message3(String name, Integer age)  {
        return "success3:" + name +age;
    }

    /**
     * 方法名为message2中的blockHandler的值
     * 方法参数必须跟原方法一致，只能多参数，不能少参数
     *
     * @param name
     * @return
     */
    public String myBlockHandler(String name, BlockException e) {
        //自定义处理逻辑
        log.error("触发block：{}", name);
        return "BlockException";
    }

    /**
     * 方法名为message2中的fallback的值
     * 方法参数必须跟原方法一致，只能多参数，不能少参数
     *
     * @param name
     * @return
     */
//    public String myThrowable(String name, Throwable e) {
//        //自定义处理逻辑
//        log.error("触发fallback：{}", name);
//        return "Throwable";
//    }

    /**
     * 下单
     * ribbon
     * @return
     */
/*    @RequestMapping("/order/prod/{pid}")
    public Order order(@PathVariable("pid") Integer pid) {
        log.info("接收到{}商品的下单请求，接下来调用商品微服务查询商品信息", pid);

        String url = "server-product";

        // 调用商品微服务查询商品信息
        Product product = restTemplate.getForObject("http://" + url + "/product/" + pid, Product.class);

        log.info("查询到{}商品的信息：{}",pid, JSON.toJSONString(product));

        // 下单
        Order order = new Order();
        order.setUid(1);
        order.setPid(pid);
        order.setNumber(1);
        order.setPrice(product.getPrice());

        orderService.create(order);

        return order;
    }*/



    /**
     * 下单
     * @return
     */
/*
    @RequestMapping("/order/prod/{pid}")
    public Order order(@PathVariable("pid") Integer pid) {
        log.info("接收到{}商品的下单请求，接下来调用商品微服务查询商品信息", pid);
        // 调用商品微服务查询商品信息
        List<ServiceInstance> instances = discoveryClient.getInstances("server-product");
        if (instances.size() == 0) {
            throw new RuntimeException("服务异常，请检查");
        }
        // 随机选择
        int index = new Random().nextInt(instances.size());
        ServiceInstance instance = instances.get(index);
        Product product = restTemplate.getForObject("http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + pid, Product.class);

        log.info("查询到{}商品的信息：{}",pid, JSON.toJSONString(product));

        // 下单
        Order order = new Order();
        order.setUid(1);
        order.setPid(pid);
        order.setNumber(1);
        order.setPrice(product.getPrice());

        orderService.create(order);

        return order;
    }
*/

}
